﻿using Gateway.Common.Cache;
using Gateway.Common.Consts;
using Gateway.IQuery.Common;

namespace Gateway.UI.Api.Controllers
{
    /// <summary>
    /// 通用服务
    /// </summary>
    public class CommonController(IRedisCache redisCache) : BaseController
    {
        /// <summary>
        /// 获取所有常量列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("const/list")]
        public async Task<List<ConstResult>> GetConstList()
        {
            string key = CacheKeys.SystemConstList;
            List<ConstResult> constResults = redisCache.Get<List<ConstResult>>(key);
            if (constResults == null)
            {
                var typeList = GetConstAttributeList();
                constResults = typeList.Select(u => new ConstResult
                {
                    Name = u.CustomAttributes.ToList().FirstOrDefault()?.ConstructorArguments.ToList().FirstOrDefault()
                        .Value?.ToString() ?? u.Name,
                    Code = u.Name,
                    Data = GetData(Convert.ToString(u.Name))
                }).ToList();
                await redisCache.AddAsync(key, constResults, TimeSpan.FromHours(2));
            }

            return await Task.FromResult(constResults);
        }

        /// <summary>
        /// 根据类名获取常量数据 🔖
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        [HttpGet("const/key")]
        public async Task<List<ConstResult>> GetData(string typeName)
        {
            string key = CacheKeys.SystemKeyConstList + $"{typeName.ToUpper()}";
            var constList =await redisCache.GetAsync<List<ConstResult>>(key);
            if (constList == null)
            {
                var typeList = GetConstAttributeList();
                var type = typeList.FirstOrDefault(u => u.Name == typeName)!;

                var isEnum = type.BaseType!.Name == "Enum";
                IEnumerable<FieldInfo> enumerable;
                if (isEnum)
                {
                    enumerable = type.GetFields()?
                        .Where(u => u.FieldType.Name == typeName);
                }
                else
                {
                    enumerable = type.GetFields();
                }

                constList = enumerable
                    .Select(u => new ConstResult
                    {
                        Name = u.Name,
                        Code = isEnum ? (int)u.GetValue(BindingFlags.Instance) : u.GetValue(BindingFlags.Instance)
                    }).ToList();
            }

            return constList;
        }

        /// <summary>
        /// 获取常量特性类型列表
        /// </summary>
        /// <returns></returns>
        private List<Type> GetConstAttributeList()
        {
            return AppDomain.CurrentDomain.GetAssemblies().SelectMany(u => u.GetTypes())
                .Where(u => u.CustomAttributes.Any(c => c.AttributeType == typeof(ConstAttribute))).ToList();
        }
    }
}